package com.android.gilastv.ui.activity;

import android.util.Pair;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.android.baselibrary.interface_.CommCallBack;
import com.android.baselibrary.interface_.OkHttpCallBack;
import com.android.baselibrary.responce.BaseResponce;
import com.android.baselibrary.tool.CommToast;
import com.android.baselibrary.tool.Log;
import com.android.baselibrary.view.MultiStateView;
import com.android.gilastv.R;
import com.android.gilastv.adapter.HomeVideoListAdapter;
import com.android.gilastv.bean.CommVideoInfo;
import com.android.gilastv.bean.HistoryInfo;
import com.android.gilastv.bean.MenuInfo;
import com.android.gilastv.constants.Constants;
import com.android.gilastv.dialog.Qingxidu_DialogFragment;
import com.android.gilastv.dialog.XuanJi_DialogFragment;

import org.litepal.LitePal;
import org.song.videoplayer.event.Event_Home_Visible;

import com.android.gilastv.event.Event_VideoDetail_PlayVideo;
import com.android.gilastv.manager.API_Manager;
import com.android.gilastv.ui.view.Comm_HeadStateView;
import com.android.gilastv.ui.view.Home_MenuView;
import com.android.gilastv.ui.view.OnViewPagerListener;
import com.android.gilastv.ui.view.ViewPagerLayoutManager;
import com.google.gson.Gson;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.song.videoplayer.DemoQSVideoView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class HomeActivity extends BaseActivity {

    @BindView(R.id.multiplestatusView)
    MultiStateView multiplestatusView;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.smartrefreshlayout)
    SmartRefreshLayout smartrefreshlayout;
    @BindView(R.id.menuview)
    Home_MenuView menuview;
    @BindView(R.id.head_stateview)
    Comm_HeadStateView head_stateview;


    ViewPagerLayoutManager mViewPagerLayoutManager;
    HomeVideoListAdapter adapter;
    int page = 1;
    int size = 20;

    //    VideoView mVideoView;
//    TikTokController mController;
    DemoQSVideoView qsVideoView;
    int mCurPos;
    int mIndex;
    List<CommVideoInfo> videoList = new ArrayList<>();
    MenuInfo menuInfo;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    protected boolean isRegistEventbus() {
        return true;
    }

    @Override
    protected void initView() {
        mViewPagerLayoutManager = new ViewPagerLayoutManager(this, OrientationHelper.VERTICAL);
        recyclerview.setLayoutManager(mViewPagerLayoutManager);
        adapter = new HomeVideoListAdapter(mContext, callBack);
        recyclerview.setAdapter(adapter);

        smartrefreshlayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData();
            }
        });
        smartrefreshlayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMoreData();
            }
        });


//        mVideoView = new VideoView(this);
//        //以下只能二选一，看你的需求
////        mVideoView.setRenderViewFactory(TikTokRenderViewFactory.create());
//        mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_CENTER_CROP);
//        mVideoView.setLooping(true);
//        mController = new TikTokController(this);
//        mVideoView.setVideoController(mController);


        mViewPagerLayoutManager.setOnViewPagerListener(new OnViewPagerListener() {
            @Override
            public void onInitComplete() {
                //自动播放第index条
                mCurPos = 0;
                startPlay();
            }

            @Override
            public void onPageRelease(boolean isNext, int position) {
                if (mCurPos == position) {
//                    mVideoView.release();
                }
            }

            @Override
            public void onPageSelected(int position, boolean isBottom) {
                if (mCurPos == position) return;
                mCurPos = position;
                startPlay();

                int LastVisibleItem = ((ViewPagerLayoutManager) recyclerview.getLayoutManager()).findLastVisibleItemPosition();
                Log.i("LastVisibleItem:" + LastVisibleItem+ "  adapter.getItemCount():"+ adapter.getItemCount());
                if (LastVisibleItem > adapter.getItemCount() - 3) {
//                    if (!isEnd && !isLoading) {
//                        pageNo++;
//                    }
                    loadMoreData();
                }
            }
        });
        //菜单点击
        menuview.setCallBack(new CommCallBack() {
            @Override
            public void onResult(Object obj) {
                stopPlay();   //点击菜单，先结束播放
                menuInfo = (MenuInfo) obj;
                refreshData();

                smartrefreshlayout.setEnableLoadMore(true);
                smartrefreshlayout.setEnableRefresh(true);
            }
        });

        recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int LastVisibleItem = ((ViewPagerLayoutManager) recyclerview.getLayoutManager()).findLastVisibleItemPosition();
//                Log.i("LastVisibleItem:" + LastVisibleItem);
//                if (LastVisibleItem > adapter.getItemCount() - 6) {
//                    if (!isEnd && !isLoading) {
//                        pageNo ++;
//                        getData();
//                    }
//                }
            }
        });
    }

    //下拉刷新
    private void refreshData() {
        videoList.clear();
        adapter.notifyDataSetChanged();
        if (menuInfo == null) return;
        if ("推荐".equals(menuInfo.dataLabel)) {
            recommendList();
        } else {
            queryVideos(menuInfo.dataId);
        }
    }

    //上拉加载
    private void loadMoreData() {
        if (menuInfo == null) return;
        if ("推荐".equals(menuInfo.dataLabel)) {
            recommendList();
        } else {
            queryVideos(menuInfo.dataId);
        }
    }

    CommCallBack callBack = new CommCallBack() {
        @Override
        public void onResult(Object obj) {
            Pair<String, CommVideoInfo> infoPair = (Pair<String, CommVideoInfo>) obj;
            CommVideoInfo info = infoPair.second;
            if ("qingxidu".equals(infoPair.first)) {
                //选清晰度
                Qingxidu_DialogFragment.showDialog((FragmentActivity) mContext, null);
            } else if ("xuanji".equals(infoPair.first)) {
                //选集数
                Map<String, Object> params = new HashMap<>();
                params.put("videoSetsList", info.videoSetsList);
                params.put("currentSelectVideoIndex", info.currentSelectVideoIndex);
                XuanJi_DialogFragment xuanJi_dialogFragment = (XuanJi_DialogFragment) XuanJi_DialogFragment.showDialog((FragmentActivity) mContext, params);
                xuanJi_dialogFragment.setCallback(new CommCallBack() {
                    @Override
                    public void onResult(Object obj) {
                        selectVideo((int) obj);
                        xuanJi_dialogFragment.dismissWithAnim();
                    }
                });
            }
        }
    };

    //选中某一集
    private void selectVideo(int index) {
        View itemView = recyclerview.getChildAt(0);
        HomeVideoListAdapter.ContentViewHolder viewHolder = (HomeVideoListAdapter.ContentViewHolder) itemView.getTag();
        CommVideoInfo info = videoList.get(mCurPos);
        if (info.currentSelectVideoIndex == index) return;  //如果选了同一集，不处理
        info.currentSelectVideoIndex = index;
        try {
            viewHolder.qs_videoview.setUp(info.getVideoUrl(info.videoSetsList.get(info.currentSelectVideoIndex).fileId), info.hanyuName);
            startPlay();
        } catch (Exception e) {

        }
    }

    //结束播放
    private void stopPlay() {
        if (qsVideoView != null) {
            qsVideoView.release();
        }
    }

    //开始播放
    private void startPlay() {
        stopPlay();

        View itemView = recyclerview.getChildAt(0);
        HomeVideoListAdapter.ContentViewHolder viewHolder = (HomeVideoListAdapter.ContentViewHolder) itemView.getTag();
        qsVideoView = viewHolder.qs_videoview;
        qsVideoView.play();

        //将当前播放视频存入本地历史记录
        CommVideoInfo info = videoList.get(mCurPos);
        List<HistoryInfo> historyInfos = LitePal.where("videoId == ?", info.id).find(HistoryInfo.class);
//        Log.i("historyInfos:" + historyInfos.size());
        if (historyInfos.size() == 0) {
            HistoryInfo historyInfo = new HistoryInfo();
            historyInfo.json = new Gson().toJson(info);
            historyInfo.videoId = info.id;
            historyInfo.save();
            Log.i("新增历史记录");
        }
    }

//    private void startPlay(int position) {
//        View itemView = recyclerview.getChildAt(0);
//        HomeVideoListAdapter.ContentViewHolder viewHolder = (HomeVideoListAdapter.ContentViewHolder) itemView.getTag();
//        mVideoView.release();
//        removeViewFormParent(mVideoView);
//        CommVideoInfo item = videoList.get(position);
////        if (item.currentVideoSet == null) item.currentVideoSet = item.videoSetsList.get(0);
//        Log.i("startPlay: " + "position: " + position + "  url: " + item.url);
////        mVideoView.setUrl(item.url);
//        //请点进去看isDissociate的解释
////        mController.addControlComponent(new PrepareView(mContext), true);
////        mController.addControlComponent(viewHolder.previewView, true);
////        mController.addControlComponent(viewHolder.mTikTokView, true);
//
//        viewHolder.rl_container.addView(mVideoView, 0);
//
//        mCurPos = position;
//
//        try {
//            String url = Config.SERVER_HOST + "/openapi/video/videoplay/" + item.videoSetsList.get(item.currentSelectVideo).sdFileId;
//            Log.i("url:" + url);
//            mVideoView.setUrl(url);
//            mVideoView.start();
//
//            HistoryInfo historyInfo = new HistoryInfo();
//            historyInfo.json = new Gson().toJson(item);
//            historyInfo.id = Long.valueOf(item.id);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    @Override
    protected void initData() {
        getData();
    }

    private void getData() {
        //获取视频分类
        API_Manager.videoTypesList(mContext, new OkHttpCallBack<BaseResponce<List<MenuInfo>>>() {
            @Override
            public void onSuccess(BaseResponce<List<MenuInfo>> baseResponce) {
                baseResponce.getData().add(0, new MenuInfo("推荐"));
                menuview.setData(baseResponce.getData());
                menuview.setSelect(0);
            }

            @Override
            public void onFailure(BaseResponce<List<MenuInfo>> baseResponce) {
                CommToast.showToast(mContext, Constants.NetError);
            }
        });
    }

    //获取视频列表
    private void recommendList() {
        API_Manager.recommendList(mContext, page, size, new OkHttpCallBack<BaseResponce<List<CommVideoInfo>>>() {
            @Override
            public void onSuccess(BaseResponce<List<CommVideoInfo>> baseResponce) {
                videoList.addAll(baseResponce.getData());
                adapter.setData(videoList);

                Log.i("videoList.size:" + videoList.size());
                multiplestatusView.setViewState(MultiStateView.ViewState.CONTENT);
                smartrefreshlayout.finishRefresh();
                smartrefreshlayout.finishLoadMore();

            }

            @Override
            public void onFailure(BaseResponce<List<CommVideoInfo>> baseResponce) {
                multiplestatusView.setViewState(MultiStateView.ViewState.ERROR);
                CommToast.showToast(mContext, Constants.NetError);
                smartrefreshlayout.finishRefresh();
                smartrefreshlayout.finishLoadMore();
            }
        });
    }

    //获取分类下视频
    private void queryVideos(String id) {
        //获取视频分类
        API_Manager.queryVideos(mContext, page, size, "", id, new OkHttpCallBack<BaseResponce<List<CommVideoInfo>>>() {
            @Override
            public void onSuccess(BaseResponce<List<CommVideoInfo>> baseResponce) {
                videoList.addAll(baseResponce.getData());
                adapter.setData(videoList);

                Log.i("videoList.size:" + videoList.size());
                multiplestatusView.setViewState(MultiStateView.ViewState.CONTENT);
                smartrefreshlayout.finishRefresh();
                smartrefreshlayout.finishLoadMore();
            }

            @Override
            public void onFailure(BaseResponce<List<CommVideoInfo>> baseResponce) {
                CommToast.showToast(mContext, Constants.NetError);
                smartrefreshlayout.finishRefresh();
                smartrefreshlayout.finishLoadMore();
            }
        });
    }

    //    @OnClick({R.id.tv_sendcode})
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.tv_sendcode:
//                break;
//        }
//    }

    //首页控件消失事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event_Home_Visible event) {
        try {
            if (event.isVisible) {
                menuview.setVisibility(View.VISIBLE);
//                head_stateview.setVisibility(View.VISIBLE);
            } else {
                menuview.setVisibility(View.GONE);
//                head_stateview.setVisibility(View.GONE);
            }
//            adapter.setControllerIsVisible(event.isVisible);
            adapter.setViewVisible(event.isVisible);
        } catch (Exception e) {

        }
    }

    //登录失效事件

    private boolean playFlag;//记录退出时播放状态 回来的时候继续播放

    @Override
    public void onResume() {
        super.onResume();
        if (qsVideoView != null) {
            if (playFlag)
                qsVideoView.play();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //暂停
        if (qsVideoView != null) {
            playFlag = qsVideoView.isPlaying();
            qsVideoView.pause();
        }
    }


    //视频详情页点击播放事件， 除了首页 其他页面都关闭
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event_VideoDetail_PlayVideo event) {
        Log.i("首页收到视频的播放事件");

        videoList.clear();
        videoList.add(event.videoInfo);
        adapter.setData(videoList);

        //首页菜单  取消选中
        menuview.setSelect(-1);
        //播放单个视频，禁用上下拉刷新
        smartrefreshlayout.setEnableLoadMore(false);
        smartrefreshlayout.setEnableRefresh(false);


    }
}
